package com.paipai.controller;

import com.paipai.feign.UserFeign;
import com.paipai.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user")
@Controller
public class UserController {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private RedisTemplate<String, Object> RedisTemplate;


    @RequestMapping("/login")
    @ResponseBody
    public Map<String, String> login(String name, String password, HttpServletResponse response) {
        Map<String, String> map = new HashMap<String, String>();
        map = userFeign.login(name, password);
        if (!map.containsKey("error")) {
            CookieUtils.deleteUserTokenFromCookie("PAI" + name,response);
            RedisTemplate.opsForValue().set("PAI" + name, map, 10, TimeUnit.MINUTES);
        }
        RedisTemplate.opsForValue().get("PAI" + name);
        return map;
    }

    @RequestMapping("checkLogin")
    @ResponseBody
    public String checkLogin(HttpServletResponse response, HttpServletRequest request){
        String checkId = CookieUtils.getCookie("checkId",request);
        String uaername = CookieUtils.getCookie("account",request);
        if(!(RedisTemplate.opsForValue().get("PAI"+uaername) ==null)){
        Map<String,String> map=(Map<String, String>) RedisTemplate.opsForValue().get("PAI"+uaername);
        String redisUUId = map.get("uuid");
        if(!checkId.equals(redisUUId)){
            CookieUtils.deleteUserTokenFromCookie( "token",response);
            CookieUtils.deleteUserTokenFromCookie( "checkId",response);
            CookieUtils.deleteUserTokenFromCookie( "account",response);
            return "delete";
        }else {
            return "ok";
        }}else {
            CookieUtils.deleteUserTokenFromCookie( "token",response);
            CookieUtils.deleteUserTokenFromCookie( "checkId",response);
            CookieUtils.deleteUserTokenFromCookie( "account",response);
            return "logout";
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public String register(String username, String password, String tel, String emailCode, String email) {
        return userFeign.register(username, password, tel, emailCode, email);
    }

    @RequestMapping("/sendEmail")
    @ResponseBody
    public String sendEmail(String email) {
        return userFeign.sendEmail(email);
    }

    @RequestMapping("/getUserByName")
    public String getUserByName(HttpServletRequest request){
        return userFeign.getUserByName();
    }
}
